java使用elasticsearch分组进行聚合查询(group by) 您所在的位置:网站首页 es count java java使用elasticsearch分组进行聚合查询(group by)

java使用elasticsearch分组进行聚合查询(group by)

2023-06-07 11:30| 来源: 网络整理| 查看: 265

java连接elasticsearch 进行聚合查询进行相应操作

一:对单个字段进行分组求和

1、表结构图片:

根据任务id分组,分别统计出每个任务id下有多少个文字标题

1.SQL:select id, count(*) as sum from task group by taskid;  

java ES连接工具类

public class ESClientConnectionUtil { public static TransportClient client=null; public final static String HOST = "192.168.200.211"; //服务器部署 public final static Integer PORT = 9301; //端口 public static TransportClient getESClient(){ System.setProperty("es.set.netty.runtime.available.processors", "false"); if (client == null) { synchronized (ESClientConnectionUtil.class) { try { //设置集群名称 Settings settings = Settings.builder().put("cluster.name", "es5").put("client.transport.sniff", true).build(); //创建client client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(HOST), PORT)); } catch (Exception ex) { ex.printStackTrace(); System.out.println(ex.getMessage()); } } } return client; } public static TransportClient getESClientConnection(){ if (client == null) { System.setProperty("es.set.netty.runtime.available.processors", "false"); try { //设置集群名称 Settings settings = Settings.builder().put("cluster.name", "es5").put("client.transport.sniff", true).build(); //创建client client = new PreBuiltTransportClient(settings).addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(HOST), PORT)); } catch (Exception ex) { ex.printStackTrace(); System.out.println(ex.getMessage()); } } return client; } //判断索引是否存在 public static boolean judgeIndex(String index){ client= getESClientConnection(); IndicesAdminClient adminClient; //查询索引是否存在 adminClient= client.admin().indices(); IndicesExistsRequest request = new IndicesExistsRequest(index); IndicesExistsResponse responses = adminClient.exists(request).actionGet(); if (responses.isExists()) { return true; } return false; } }

 

java ES语句(根据单列进行分组求和)

//根据 任务id分组进行求和 SearchRequestBuilder sbuilder = client.prepareSearch("hottopic").setTypes("hot");//根据taskid进行分组统计,统计出的列别名叫sum TermsAggregationBuilder termsBuilder = AggregationBuilders.terms("sum").field("taskid"); sbuilder.addAggregation(termsBuilder); SearchResponse responses= sbuilder.execute().actionGet(); //得到这个分组的数据集合 Terms terms = responses.getAggregations().get("sum"); List lists = new ArrayList(); for(int i=0;i


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有